<?php
namespace app\index\controller;

use app\index\model\Article as ArticleModel;
use app\index\model\Category as CategoryModel;
use app\common\controller\HomeBase;
use think\Cache;
use app\index\model\Guestbook;
use think\Db;

class article extends HomeBase {


    protected $category_model;
    protected $article_model;
    protected $guest_model;


    protected function _initialize() {

        parent::_initialize();
        $this->article_model  = new ArticleModel();
        $this->category_model = new CategoryModel();
        $this->guest_model  = new Guestbook();

    }


    public function index($id=0) {

           if ($id==0) {
             $this->error('请选择需要的文章');
        }

       
         //取文章主体
      $article = $this->article_model->find($id);

       if(!$article)
       {
    
       $this->error('文章不存在！');
       }

         if(!Cache::get(getIPaddress().$id))
         {
         Cache::set(getIPaddress().$id,getIPaddress().$id,3600);
         $this->article_model->where('id',$id)->setInc('reading');
         }
        empty($article['keywords'])?$em=1: $em =0;
         $tags_arr = [];
         $k_tags = explode(",",$article['keywords']);
        foreach ( $k_tags as $k=>$v) {
            $tags_arr[$k]['ta_name'] = $v;
        }
        //取类别名称
         $getcategoryName = $this->category_model->column('name', 'id');
        
        //上一篇
        $prevs  = $this->article_model->field('id,title')->where(array('cid'=>$article['cid']))->where('id<'.$id)->order('id desc')->find();
         //下一篇
        $nexts  = $this->article_model->field('id,title')->where(array('cid'=>$article['cid']))->where('id>'.$id)->order('id asc')->find();

         //相关文章

         $map['id']  = array('neq',$id);

         $article_related  = $this->article_model->field('id,title')->where(array('cid'=>$article['cid']))->where($map)->order('id desc')->limit(10)->select();
         //获取文章的评论
        $commentList = $this->guest_model->where("p_id =0 AND a_id=".$id)->select();
        foreach ( $commentList as $k=>$v ) {
            $sql = " SELECT * FROM think_guestbook WHERE a_id=$id AND s_id=".$v['id']." ORDER BY id asc";
            $list = Db::query($sql);
            foreach ( $list as $key=>$value ) {
                $ff = $this->guest_model->where('id='.$value['p_id'])->find();
                $list[$key]['user_name'] = $ff['nickname'];
                $list[$key]['pub_time'] = dayfast($value['create_time']);
            }
            $commentList[$k]['user'] = $list;
            $commentList[$k]['pub_time'] = dayfast($v['create_time']);
        }
        return $this->fetch('index', [
            'article' => $article,
            'k_tags'=>$tags_arr,
            'prevs' => $prevs,
            'nexts' => $nexts,
            'em' =>$em,
            'getcategoryName' => $getcategoryName,
            'article_related' => $article_related,
            'comment_list' => $commentList
        ]);


    }

}
